package com.muh.exchange;

import com.muh.util.RabbitMQUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicConsumer {
    private static final String EXCHANGE_NAME = "topicExchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);//必须要是 topic 类型
        String queueName = channel.queueDeclare().getQueue();//临时对列
        /**
         * #：匹配一个或者多个词，例如lazy.# 可以匹配 lazy.xxx 或者 lazy.xxx.xxx
         * *：只能匹配一个词，例如lazy.* 只能匹配 lazy.xxx
         */
        channel.queueBind(queueName, EXCHANGE_NAME, "*.info");//交换机绑定对列
        channel.queueBind(queueName, EXCHANGE_NAME, "#.debug");//交换机绑定对列

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("---------------------------");
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("contentType: " + properties.getContentType());
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag: " + deliveryTag);
                System.out.println("content: " + new String(body, "UTF-8"));
//                channel.basicAck(deliveryTag, false);
                System.out.println("---------------------------");
            }
        };
        channel.basicConsume(queueName, true, consumer);//自动应答临时对列的名称
    }
}
